import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, Link, useLocation } from 'react-router-dom';
import './App.css';
import Login from './components/Login';
import Register from './components/Register';
import Home from './pages/Home';
import Department from './pages/Department';
import Course from './pages/Course';
import Enrollment from './pages/Enrollment';
import Friend from './pages/Friend';
import Transfer from './pages/Transfer';
import Message from './pages/Message';
import { useAuth } from './context/AuthContext';

function RequireAuth({ children }) {
  const { user } = useAuth();
  const location = useLocation();
  if (!user) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
  return children;
}

function App() {
  return (
    <Router>
      <div className="navbar">
        <Link to="/home">首页</Link>
        <Link to="/department">院系管理</Link>
        <Link to="/course">课程管理</Link>
        <Link to="/enrollment">选课与成绩</Link>
        <Link to="/friend">好友管理</Link>
        <Link to="/transfer">好友转账</Link>
        <Link to="/message">好友消息</Link>
        <Link to="/login" style={{ marginLeft: 'auto' }}>登录</Link>
        <Link to="/register">注册</Link>
      </div>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />
        <Route path="/home" element={<RequireAuth><Home /></RequireAuth>} />
        <Route path="/department" element={<RequireAuth><Department /></RequireAuth>} />
        <Route path="/course" element={<RequireAuth><Course /></RequireAuth>} />
        <Route path="/enrollment" element={<RequireAuth><Enrollment /></RequireAuth>} />
        <Route path="/friend" element={<RequireAuth><Friend /></RequireAuth>} />
        <Route path="/transfer" element={<RequireAuth><Transfer /></RequireAuth>} />
        <Route path="/message" element={<RequireAuth><Message /></RequireAuth>} />
        <Route path="/" element={<Navigate to="/login" />} />
      </Routes>
    </Router>
  );
}

export default App; 